/**
 * 
 */
package com.priox.sigar.application.writer;

import com.priox.sigar.client.dto.CuentaContableDTO;
import com.priox.sigar.domain.model.AgrupacionRepository;
import com.priox.sigar.util.TimeObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author acogoluegnes
 *
 */
@Component
public class CuentaContableItemWriter implements ItemWriter<CuentaContableDTO> {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CuentaContableItemWriter.class);

    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void init() {
        jdbcTemplate=new JdbcTemplate(dataSource);
    }

	/* (non-Javadoc)
	 * @see org.springframework.batch.item.ItemWriter#write(java.util.List)
	 */
	@Override
	public void write(final List<? extends CuentaContableDTO> items) throws Exception {
        String sql = "insert into dbo.SGTM_CUENTA_CONTABLE (cuenta_contable_id,descripcion,CREADO_POR,FECHA_CREACION,OPCION,ESTADO) values (?,?,'SISTEMA',GETDATE(),0,1)";

        TimeObserver timeObserver = new TimeObserver("insert del bloque en ");
        timeObserver.empezar();
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {

            @Override
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                CuentaContableDTO customer = items.get(i);
                ps.setString(1, customer.getCuentaContableId());
                ps.setString(2, customer.getDescripcion());

            }

            @Override
            public int getBatchSize() {
                return items.size();
            }
        });

        timeObserver.terminar();
        System.out.println(timeObserver.mostrarMsg());
    }

}
